import Vue from "vue";
import Router from "vue-router";
import store from "../store";
import { Message } from 'element-ui';


Vue.use(Router);

const router = new Router({
  mode: 'history', // 去掉'#'
  routes: [{
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    name: 'login',
    component: () =>
      import("@/views/login/index"),
    meta: {
      title: "登陆"
    }
  },
  {
    path: "/home",
    name: 'home',
    component: () =>
      import("@/views/home/index"),
    meta: {
      title: "首页",
      // 缓存首页
      keepAlive: true,
      needLogin: true
    },
    redirect: '/home/select',
    children: [{
      path: 'select',
      name: 'select',
      component: () =>
        import("@/views/home/children/select/index"),
      meta: {
        title: '主页',
        needLogin: true
      }
    }]
  },
  {
    path: "*",
    component: () =>
      import("@/components/NotFound")
  }
  ]
});

// 路由门卫
router.beforeEach((to, from, next) => {
  let { title, needLogin } = to.meta; // 页面标题
  if (to.name == 'login') {  // 跳转到登录页面清除缓存
    // 清空缓存
    $cookies.remove('totalInfo')
    store.commit('updateToken', null);
    next();
    return
  }
  // 获取登录状态
  document.title = title;
  if (needLogin && (!$cookies.get('totalInfo') || !store.state.token)) {
    console.log(!$cookies.get('totalInfo'), "!$cookies.get('totalInfo')", !store.state.token, '!store.state.token');
    console.log('用户不存在，请重新登录');
    // 提示
    Message({
      type: 'error',
      message: '用户不存在，请重新登录',
      duration: 1500
    });
    // 跳转
    next({
      path: "/login"
    });
  } else {
    console.log('已登录');
    next();
  }
});

export default router;